<?php
/*
 * http://bakery.cakephp.org/articles/view/ticket-component-resetting-user-passwords
 * https://trac.cakephp.org/ticket/3131
 * http://sliceofcake.wordpress.com/2007/09/20/loadmodel/
 */
class SystemTicketComponent extends Object
{

	function initialize(&$controller) {
		App::import('Model', 'SystemTicket');
	}

	function startup(&$controller) {
		$this->controller = $controller;
		$this->garbage();
	}

	// Create a new ticket by providing the data to be stored in the ticket.
	function set($info = null) {
		if ($info) {
			$ticketObj = new SystemTicket();
			
			$data['SystemTicket']['hash'] = md5( (time() - rand(100, 999) + rand(1000, 2000)) );
			$data['SystemTicket']['data'] = $info;

			if ($ticketObj->save($data)) {
				return $data['SystemTicket']['hash'];
			}
		}
		return false;
	}

	// Return the value stored or false if the ticket can not be found.
	function get($ticket = null) {
		if ($ticket) {
			$ticketObj = new SystemTicket();
			
			$data = $ticketObj->findByHash($ticket);
			
			if (is_array($data) && is_array($data['SystemTicket'])) {
				// optionally auto-delete the ticket -> this->delete($ticket);
				return $data['SystemTicket']['data'];
			}
			
		}
		return false;
	}

	// Delete a used ticket
	function del($ticket = null) {
		if ($ticket) {
			$ticketObj = new SystemTicket();
			
			$data = $ticketObj->findByHash($ticket);
			if ( is_array($data) && is_array($data['SystemTicket']) ) {
				return $data = $ticketObj->delete($data['SystemTicket']['id']);
			}
		}
		return false;
	}

	// Remove old tickets
	function garbage() {
		$deadline = date('Y-m-d H:i:s', time() - (24 * 60 * 60)); // keep tickets for 24h.

		$ticketObj = new SystemTicket();
		
		$data = $ticketObj->query('DELETE FROM `system_tickets` WHERE `created` < \''.$deadline.'\'');
	}
}

?>